package com.base.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.PostConstruct;

import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseDao<T> extends SqlSessionDaoSupport {
	
	private Class<?> entityClass;
	private String entityName;
	@Autowired
	private SqlSessionTemplate sqlSession;
	
	@PostConstruct
	public void init() {
		super.setSqlSessionTemplate(sqlSession);
	}
	
	@SuppressWarnings("unchecked")
	public BaseDao() {
		Class<?> c = getClass(); 
		Type type = c.getGenericSuperclass();
		if (type instanceof ParameterizedType) { 
			Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments(); 
			entityClass = (Class<T>) parameterizedType[0]; 
			entityName = "com.base.mapper." + entityClass.getSimpleName() + "Mapper";
        }
	}
	
	public int insert(Object parameter) {
		return sqlSession.insert(entityName+".insert", parameter);
	}
	
	public int updateById(Object parameter) {
		return sqlSession.update(entityName+".updateById", parameter);
	}
	
	public int deleteById(Object parameter) {
		return sqlSession.delete(entityName+".deleteById", parameter);
	}
	
	public T selectById(Object parameter) {
		return sqlSession.selectOne(entityName+".selectById", parameter);
	}
	
	public List<T> selectList(Object parameter) {
		return sqlSession.selectList(entityName+".selectList", parameter);
	}
	
}
